<?php
namespace frontend\controllers;

use Yii;
use frontend\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use frontend\models\TaoZhuang;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use frontend\views\site\IndexCell;
use frontend\models\SysItem;
use backend\models\Show;
use yii\db\ActiveRecord;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup','account'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout','account'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    private function indexSqls($tz,$item,$showHome)
    {
        
        $recent_tz_sql="SELECT taozhuang.sid as id,taozhuang.`name`,taozhuang.top_time AS uptime,middle_img.url AS middle_img_url,small_img.url AS small_img_url,large_img.url AS large_img_url
            FROM taozhuang,sys_image small_img,sys_image large_img,sys_image middle_img
            WHERE taozhuang.app_return=1 AND taozhuang.img_small_id=small_img.id AND taozhuang.img_url_id=large_img.id AND taozhuang.img_thumb_id=middle_img.id
            ORDER BY taozhuang.sid DESC LIMIT ".$tz['offset'].",".$tz['limit'];
        $recent_item_sql="SELECT sys_item.id,sys_item.`name`,sys_item.update_at AS uptime,small_img.url AS small_img_url,middle_img.url AS middle_img_url,large_img.url AS large_img_url
    	    FROM `sys_item`,sys_image small_img,sys_image middle_img,sys_image large_img
    	    WHERE sys_item.app_return=1 AND sys_item.img_small_id=small_img.id AND sys_item.img_thumb_id=middle_img.id AND
    	    sys_item.img_url_id=large_img.id ORDER BY sys_item.top_time DESC, sys_item.id DESC LIMIT ".$item['offset'].",".$item['limit'];
        $recent_showHome_sql="SELECT `show`.id,`show`.`name`,`show`.publish_time AS uptime,small_img.url AS small_img_url,middle_img.url AS middle_img_url,large_img.url AS large_img_url
    	    FROM `show`,sys_image small_img,sys_image middle_img,sys_image large_img
    	    WHERE `show`.app_return=1 AND `show`.img_small_id=small_img.id AND `show`.img_thumb_id=middle_img.id AND `show`.img_url_id=large_img.id 
            ORDER BY `show`.id DESC LIMIT ".$showHome['offset'].",".$showHome['limit'];
        $recent_tz=TaoZhuang::findBySql($recent_tz_sql)->asArray()->all();
        $recent_item=SysItem::findBySql($recent_item_sql)->asArray()->all();
        $recent_showHome=Show::findBySql($recent_showHome_sql)->asArray()->all();
        return [
            'tz'=>$recent_tz,
            'item'=>$recent_item,
            'showHome'=>$recent_showHome
        ];
    }
    private function indexRandOrder($indexCellObj,$sqlData,$cellLayoutArray)
    {
        $item=$sqlData['item'];
        $tz=$sqlData['tz'];
        $showHome=$sqlData['showHome'];
        $data=array();
        for ($i=0,$j=0,$item_count=0,$tz_count=0,$showHome_count=0;$i<count($cellLayoutArray);$i++)
        {
            if ($cellLayoutArray[$i]==1)
            {
                if (intval(rand(0,2)))
                {
                    if ($item_count<count($item))
                    {
                        $data[$j++]=$indexCellObj->setData($item[$item_count++], 'item');
                    }
                    elseif ($tz_count<count($tz))
                    {
                        $data[$j++]=$indexCellObj->setData($tz[$tz_count++], 'tz');
                    }
                }
                else
                {
                    if ($tz_count<count($tz))
                    {
                        $data[$j++]=$indexCellObj->setData($tz[$tz_count++], 'tz');
                    }
                    elseif ($item_count<count($item))
                    {
                        $data[$j++]=$indexCellObj->setData($item[$item_count++], 'item');
                    }
                }
            }
            elseif ($cellLayoutArray[$i]==2)
            {
                if ($tz_count<count($tz))
                {
                    $data[$j++]=$indexCellObj->setData($tz[$tz_count++], 'tz');
                }
                elseif ($item_count<count($item))
                {
                    $data[$j++]=$indexCellObj->setData($item[$item_count++], 'item');
                }
            }
            elseif ($cellLayoutArray[$i==3])
            {
                if ($showHome_count<count($showHome))
                {
                    $data[$j++]=$indexCellObj->setData($showHome[$showHome_count++], 'artical');
                }
                elseif ($tz_count<count($tz))
                {
                    $data[$j++]=$indexCellObj->setData($tz[$tz_count++], 'tz');
                }
                elseif ($item_count<count($item))
                {
                    $data[$j++]=$indexCellObj->setData($item[$item_count++], 'item');
                }
            }
        }
        return [
            'data'=>$data,
            'counts'=>[
        	    'item_count'=>$item_count,
        	    'showHome_count'=>$showHome_count,
        	    'tz_count'=>$tz_count
        	]
        ];
    }
    public function actionIndex()
    {
        $sqlData=$this->indexSqls(
            [
                'offset'=>0,
                'limit'=>40
            ],
            [
                'offset'=>0,
                'limit'=>40
            ],
            [
                'offset'=>0,
                'limit'=>10
            ]
        );
    	
    	$indexCellObj = new IndexCell();
    	$cellLayoutArray=[
    	    3,
    	    1,1,1,
    	    1,2,
    	    1,1,1,
    	    1,1,1,
    	    3,
    	    2,1,
    	    1,1,1,
    	    1,1,1,
    	    1,2,
    	    3,
    	    1,1,1,
    	    1,2,
    	    1,1,1,
    	    1,1,1,
    	    2,1,
    	    1,1,1,
    	    1,1,1,
    	    1,1,1
    	];
    	$orderResult=$this->indexRandOrder($indexCellObj, $sqlData, $cellLayoutArray);

    	$indexCells=$indexCellObj->layoutAuto($cellLayoutArray, $orderResult['data']);
        return $this->render('index',[
            'indexCells'=>$indexCells,
            'counts'=>$orderResult['counts']
        ]);
    }
    
    public function actionHomePageLoadMore()
    {
        if (Yii::$app->request->isAjax&&$str=Yii::$app->request->post('counts'))
        {
            $counts=json_decode($str);
            $sqlData=$this->indexSqls(
                [
                    'offset'=>$counts->tzCount,
                    'limit'=>40
                ],
                [
                    'offset'=>$counts->itemCount,
                    'limit'=>40
                ],
                [
                    'offset'=>$counts->showHomeCount,
                    'limit'=>10
                ]
            );
            $indexCellObj=new IndexCell();
            $cellLayoutArray=[
                1,1,1,
                1,2,
                1,1,1,
                1,1,1,
                3,
                2,1,
                1,1,1,
                1,1,1,
                1,2,
                3,
                1,1,1,
                1,2,
                1,1,1,
                1,1,1,
                2,1,
                1,1,1,
                1,1,1,
                1,1,1
            ];
            $orderResult=$this->indexRandOrder($indexCellObj, $sqlData, $cellLayoutArray);
            $indexCells=$indexCellObj->layoutAuto($cellLayoutArray, $orderResult['data']);
            $str=json_encode([
                'htmlCode'=>$indexCells,
                'counts'=>$orderResult['counts']
            ]);
            echo $str;
        }
    }

    public function actionLogin()
    {
    	//return $this->redirect(['user/security/login']);
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            $res=ActiveRecord::findBySql("SELECT SUM(count) FROM `user_shopping` WHERE user_id=".Yii::$app->user->identity->id)->asArray()->all();
            Yii::$app->session['userShoppingCartCount']=$res[0]['SUM(count)'];
            return $this->goBack();
        } else {
            Yii::$app->user->setReturnUrl(Yii::$app->request->referrer);
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();
        return $this->goHome();
    }

    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    public function actionAbout()
    {
        return $this->render('about');
    }

    public function actionSignup()
    {
    	//return $this->redirect(['user/registration/register']);
        $this->layout = "main";
        $model = new SignupForm();
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model2 = new ResetPasswordForm();
            return $this->render('resetPassword', [
                'model' => $model2,
            ]);

        } else {
            return $this->render('requestPasswordResetToken', [
                'model' => $model,
            ]);
        }
    }

    public function actionResetPassword()
    {
        try {
            $model = new ResetPasswordForm();
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && !$model->error && $model->validate() && $model->resetPassword()) {
            Yii::$app->getSession()->setFlash('success', '密码设置成功');
            return $this->goHome();
        }
        
        return $this->redirect(['site/request-password-reset']);
    }
    public function actionProductList()
    {
        return $this->render('productList');
    }
    public function actionAccount()
    {
        return $this->render('account');
    }
}
